<?php
/**
 * PHP version 5
 * @copyright  Samsun Xu 2009
 * @package    Frontend
 * @license    LGPL
 * @get product list
 */
session_start();
define('TL_ROOT', dirname(__FILE__));

require_once('system/config/localconfig.php');

class userClass
{	
	public function run()
	{
		$action	= $_POST['FORM_SUBMIT'];
		switch($action){
			case "tl_registration":
				$return_code  = $this->registration();
				break;
		}

		echo $return_code;
	}
	
	public function registration()
	{
		date_default_timezone_set("GMT");
		$time		= time();
		$email		= trim($_POST['email']);
		$password	= $_POST['password'];
		$gender		= $_POST['gender'];
		$birthday	= strtotime($_POST['birthday']." 12:00:00");
		$province	= $_POST['province'];
		$city		= $_POST['city'];
		$social		= @substr($_POST['social'],1);
		$newsletter	= intval($_POST['newsletter']);
		$currency 	= $_POST['cur'];
		
		// set new password
		$password_2 = substr(md5(uniqid('', true)), 0, 23);
		$password_1 = sha1($password_2 . $password);
		$password = "$password_1:$password_2";		
		
		$this->setDB();

		$sql		= "select count(*) as rsNum from `tl_member` where username='$email' or email='$email'";
		$result 	= @mysql_query($sql);
		$countRd 	= @mysql_fetch_assoc($result);
		
		if($countRd['rsNum']==0){
			$sql	= "INSERT INTO `tl_member` (`tstamp`, `registtime`, `dateOfBirth`, `gender`, `social`, `country`, `city`, `state`, `cur`, `email`, `username`, `groups`, `password`, `login`, `allowEmail`, newsletter, `activation`)
	VALUES ('$time', '$time', '$birthday', '$gender', '$social', 'cn', '$city', '$province', '$currency', '$email', '$email', 0x613a313a7b693a303b733a313a2231223b7d, '$password', 1, 'email_member', 0x613a313a7b693a303b733a313a2231223b7d, '');";

			$strHTML = @mysql_query($sql);
			
			// Get the insertId
			$sql = "SELECT id FROM `tl_member` WHERE `email`='$email'";
			$insertId = 0;
			$result = @mysql_query($sql);
			if ($row = @mysql_fetch_assoc($result))
			{
				$insertId = intval($row["id"]);
			}
			$time = time();
			// Make this user login.
			$strIp = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
			$sessionid = session_id();
			$hash = sha1(session_id() . (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']) . 'FE_USER_AUTH');
			$this->setCookie('FE_USER_AUTH', $hash, ($time + 3600), '');
			$sql = "INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash) VALUES ($insertId, $time, 'FE_USER_AUTH', '$sessionid', '$strIp', '$hash')";
			$strHTML = @mysql_query($sql);
			
			$shopUrl = 'http://' . $_SERVER['HTTP_HOST'] . (($GLOBALS['TL_CONFIG']['websitePath']) ? ($GLOBALS['TL_CONFIG']['websitePath']) : '');
			$shopLogo = 'http://' . $_SERVER['HTTP_HOST'] . (($GLOBALS['TL_CONFIG']['websitePath']) ? ($GLOBALS['TL_CONFIG']['websitePath']) : '') . '/images/logo_registratio.jpg';
			$shopFooters = 'http://' . $_SERVER['HTTP_HOST'] . (($GLOBALS['TL_CONFIG']['websitePath']) ? ($GLOBALS['TL_CONFIG']['websitePath']) : '') . '/images/footer_log.jpg';
			$img_email_conf = 'http://' . $_SERVER['HTTP_HOST'] . (($GLOBALS['TL_CONFIG']['websitePath']) ? ($GLOBALS['TL_CONFIG']['websitePath']) : '') . '/?inlink=email_cfm';
			
			// Backpocket added.
			if (isset($_SESSION['BACKPOCKET']) && $_SESSION['BACKPOCKET'])
			{
				$sql = "SELECT * FROM tl_backpocket WHERE id_catalog=" . $_SESSION['BACKPOCKET'][0]['id'] . " AND size='" . $_SESSION['BACKPOCKET'][0]['size'] . "' AND color='" . $_SESSION['BACKPOCKET'][0]['color'] . "' AND id_member=" . $insertId;
				$res_pocket = @mysql_query($sql);
									 
				if (!($row = mysql_fetch_assoc($res_pocket)))
				{					
					$sql = "INSERT INTO `tl_backpocket` (`id_member`, `id_catalog`, `tstamp`, `size`, `color`, `quantity`, `is_wrapping`, `wrapping_price`) VALUES ($insertId, " . $_SESSION['BACKPOCKET'][0]['id'] . ", " . $time . ", '" . $_SESSION['BACKPOCKET'][0]['size'] . "', '" . $_SESSION['BACKPOCKET'][0]['color'] . "', '" . $_SESSION['BACKPOCKET'][0]['quantity'] . "', '" . $_SESSION['BACKPOCKET'][0]['is_wrapping'] . "', " . number_format(floatval($_SESSION['BACKPOCKET'][0]['wrapping_price']), 2, '.', '') . ")";
					@mysql_query($sql);
				}
				else
				{
					$sql = "UPDATE `tl_backpocket` SET `tstamp`=" . $time . ", `size`='" . $_SESSION['BACKPOCKET'][0]['size'] . "', `color`='" . $_SESSION['BACKPOCKET'][0]['color'] . "', `quantity`='" . $_SESSION['BACKPOCKET'][0]['quantity'] . "', `is_wrapping`=" . $_SESSION['BACKPOCKET'][0]['is_wrapping'] . ", `wrapping_price`=" . number_format(floatval($_SESSION['BACKPOCKET'][0]['wrapping_price']), 2, '.', '');
					$res_pocket_update = @mysql_query($sql);
				}
				
				unset($_SESSION['BACKPOCKET']);
				
				$strHTML = '2'; 
			}
			
			require("plugins/phpmailer/class.phpmailer.php");
			if ($newsletter)
			{
				// Add new subscriptions
				$sql = "SELECT * FROM tl_newsletter_recipients WHERE email='" . $email . "'";
				$res_recipient = @mysql_query($sql);
				if ($row = @mysql_fetch_assoc($res_recipient))
				{
					
				}
				else 
				{
					$actived = false;
					$strToken = md5(uniqid('', true));
					$sql = "INSERT INTO tl_newsletter_recipients (pid, tstamp, email, active, addedOn, ip, token) VALUES (1, " . time() . ", '" . $email . "', '1', '" . time() . "', '" . $strIp . "', '')";
					@mysql_query($sql);
					// Active the recipient and send email about 30% off.
					$voucher_code = strtoupper(substr(sha1(rand(10, 200) . $time), 0, 16));
					// till the end
					$till_time = date('F d Y', $time + 30 * 3 * 24 * 3600);
					$sql = "INSERT INTO `tl_voucher` (`coupon_des`, `coupon_con`, `coupon_amount`, `coupon_method`, `discount`, `email`, `coupon_code`, `status`, `tstamp`, `coupon_from`, `coupon_to`) VALUES ('Discount off 10%', '1', '0.00', '2', '0.1', '" . $email . "', '" . $voucher_code . "', '1', '" . time() . "', '" . time() . "', '" . $till_time . "')";
					@mysql_query($sql);
					ob_start();
					include(TL_ROOT . "/system/modules/newsletter/templates/mod_voucher.tpl");
					$strBuffer = ob_get_contents();
					ob_end_clean();
					//Send email to register user.
					$mail = new PHPMailer();
					$mail->IsSMTP(); // set mailer to use SMTP
					$mail->CharSet = "utf-8";
					$mail->IsHTML(true);
					$mail->Host = "smtp.corpease.net"; // specify main and backup server
					$mail->SMTPAuth = true; // turn on SMTP authentication
					$mail->Username = "sender@daftshopping.com"; // SMTP username
					$mail->Password = "d@ftsh0ppIng"; // SMTP password
		
					$mail->From = "sender@daftshopping.com";
					$mail->FromName = "daftshoppinng.com";
					$mail->AddAddress("$email", "$email");
		
					$mail->WordWrap = 50; // set word wrap to 50 characters
		
					$mail->Subject = "Hello and welcome to Daftshopping";
					$mail->Body = $strBuffer;
					//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
		
					if(!$mail->Send())
					{
						echo "Message could not be sent. <p>";
						echo "Mailer Error: " . $mail->ErrorInfo;
						exit;
					}
					//$link_newsletter = $shopUrl . "/newsletter-acrived.html?token=" . $strToken;
				}
			}
			
			if (!$newsletter)
			{
				ob_start();
				include($_SERVER['DOCUMENT_ROOT'] . (($GLOBALS['TL_CONFIG']['websitePath']) ? ($GLOBALS['TL_CONFIG']['websitePath']) : '') . "/mails/user_reg.tpl");
				$strBuffer = ob_get_contents();
				ob_end_clean();
			
				//Send email to register user.
				$mail = new PHPMailer();
				$mail->IsSMTP(); // set mailer to use SMTP
				$mail->CharSet = "utf-8";
				$mail->IsHTML(true);
				$mail->Host = "smtp.corpease.net"; // specify main and backup server
				$mail->SMTPAuth = true; // turn on SMTP authentication
				$mail->Username = "sender@daftshopping.com"; // SMTP username
				$mail->Password = "d@ftsh0ppIng"; // SMTP password

				$mail->From = "sender@daftshopping.com";
				$mail->FromName = "daftshoppinng.com";
				$mail->AddAddress("$email", "$email");

				$mail->WordWrap = 50; // set word wrap to 50 characters

				$mail->Subject = "Hello and Welcome to Daftshopping";
				$mail->Body = $strBuffer;
				//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

				if(!$mail->Send())
				{
					echo "Message could not be sent. <p>";
					echo "Mailer Error: " . $mail->ErrorInfo;
					exit;
				}
			}
		}else{
			$strHTML = 0;
		}
		return $strHTML;
	}
	
	/**
	 * Set a cookie
	 * @param string
	 * @param mixed
	 * @param integer
	 * @param string
	 * @param string
	 * @param boolean
	 */
	private function setCookie($strName, $varValue, $intExpires, $strPath='', $strDomain=null, $blnSecure=null)
	{
		if (!strlen($strPath))
		{
			$strPath = '/';
		}

		setcookie($strName, $varValue, $intExpires, $strPath, $strDomain, $blnSecure);
	}

	public function setDB()
	{
		$strHost = $GLOBALS['TL_CONFIG']['dbHost'];
		if($GLOBALS['TL_CONFIG']['dbPort']){
			$strHost .= ':' . $GLOBALS['TL_CONFIG']['dbPort'];
		}

		if($GLOBALS['TL_CONFIG']['dbPconnect']){
			$resConnection = @mysql_pconnect($strHost, $GLOBALS['TL_CONFIG']['dbUser'], $GLOBALS['TL_CONFIG']['dbPass']);
		}else{
			$resConnection = @mysql_connect($strHost, $GLOBALS['TL_CONFIG']['dbUser'], $GLOBALS['TL_CONFIG']['dbPass']);
		}

		if (is_resource($resConnection)){
			@mysql_query("SET sql_mode=''", $resConnection);
			@mysql_query("SET NAMES " . $GLOBALS['TL_CONFIG']['dbCharset'], $resConnection);
			@mysql_select_db($GLOBALS['TL_CONFIG']['dbDatabase'], $resConnection);
		}
	}	
	
}

$objGetRd = new userClass();
$objGetRd->run();

?>